import styles from './MainScreen.module.css';
import {useCallback, useEffect, useState} from 'react';
import deckApi from "../api/deckApi";
import Deck from "../types/Deck";
import DeckResponse from "../api/types/DeckResponse";
import DrawCardsResponse, {CardResponse} from "../api/types/DrawCardsResponse";
import Card from "../types/Card";
import Suit from "../types/Suit";
import Value from "../types/Value";
import CardImage from "./CardImage";
import ConfigureDeckScreen from "./ConfigureDeckScreen";

async function getShuffledDeck(suits?: Suit[]): Promise<Deck> {
    let deckResponse: DeckResponse = await deckApi.shuffle(suits);
    let drawCardsResponse: DrawCardsResponse = await deckApi.drawCards(deckResponse.remaining);

    return new Deck(drawCardsResponse.cards.map(createCardFromResponse));
}

function createCardFromResponse(cardResponse: CardResponse) {
    return new Card(
        Value.byName(cardResponse.value),
        Suit.byName(cardResponse.suit),
        cardResponse.image
    );
}

export default function MainScreen() {
    let [deck, setDeck] = useState<Deck | null>(null);
    let [deckVersion, setDeckVersion] = useState<number>(0);
    let [activeSuits, setActiveSuits] = useState<Suit[]>([]);
    let [isConfiguring, setConfiguring] = useState<boolean>(false);
    let [isLoading, setLoading] = useState<boolean>(true);

    let onConfigure = useCallback(() => {
        setConfiguring(true);
    }, []);

    let onConfigureCancelled = useCallback(() => {
        setConfiguring(false);
    }, []);

    let onConfigureApplied = useCallback((suits: Suit[], shuffle: boolean) => {
        setConfiguring(false);
        setActiveSuits([...suits]);

        if (shuffle) {
            setLoading(true);
            setDeckVersion(version => version + 1);
        }
    }, []);

    useEffect(() => {
        setActiveSuits(Suit.ALL_SUITS.slice());
    }, []);

    useEffect(() => {
        setLoading(true);

        (async () => {
            let newDeck = await getShuffledDeck();

            setDeck(() => newDeck);
            setLoading(false);
        })();
    }, [deckVersion]);

    if (isLoading) {
        return (
            <div className={styles.mainScreen}>
                Loading...
            </div>
        );
    }

    return (
        <div className={styles.mainScreen}>
            <div className={styles.cardList}>
                {deck?.cards
                    .filter(card => activeSuits.includes(card.suit))
                    .map(card => <CardImage key={card.code} card={card} />)}
            </div>
            <button className={styles.configureButton} onClick={onConfigure}>
                Настроить колоду
            </button>
            <ConfigureDeckScreen
                opened={isConfiguring}
                initialCheckedSuits={activeSuits}
                onCancel={onConfigureCancelled}
                onApply={onConfigureApplied}
            />
        </div>
    );
}
